<template>
  <div>
    <el-card class="box-card">
      <el-row>
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/main/department' }">权限管理</el-breadcrumb-item>
          <el-breadcrumb-item>成员管理</el-breadcrumb-item>
        </el-breadcrumb>
      </el-row>
      <el-row><br><br></el-row>
      <el-row>
        <el-col :span="1"><br></el-col>
        <el-col :span="19">
          <el-form :inline="true" :model="dto" class="form-inline" ref="dtoForm">
            <el-form-item prop="uname">
              <el-input v-model="dto.uname" placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item prop="did">
              <el-select v-model="dto.did" clearable placeholder="请选择所属部门">
                <el-option
                  v-for="item in departmentList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="rid">
              <el-select v-model="dto.rid" clearable placeholder="请选择所属角色">
                <el-option
                  v-for="item in roleList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>         
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="1"><br></el-col>
        <el-col :span="12">
          <el-button type="primary" icon="el-icon-search" @click="getEmployeeList()">搜索</el-button>
          <el-button type="warning" @click="resetForm('dtoForm')">重置</el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="success" round @click="handleAdd()">添加成员</el-button>
        </el-col>
      </el-row>
      <el-row><br><br></el-row>
      <el-row>
        <el-col :span="1"><br></el-col>
        <el-col :span="22">
          <el-table
            :data="employeeList"
            style="width: 100%"
            height="340">
            <el-table-column
              label="序号"
              type="index"
              width="60">
            </el-table-column>
            <el-table-column
              prop="uname"
              label="用户名"
              width="100">
            </el-table-column>
            <el-table-column
              prop="name"
              label="姓名"
              width="100">
            </el-table-column>
            <el-table-column
              prop="role.department.name"
              label="所属部门"
              width="100">
            </el-table-column>
            <el-table-column
              prop="role.name"
              label="所属角色"
              width="100">
            </el-table-column>
            <el-table-column
              prop="phone"
              label="手机号"
              width="120">
            </el-table-column>
            <el-table-column
              prop="status"
              label="状态"
              width="100">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.lockstate == 1" type="success">正常</el-tag>
                <el-tag v-else type="danger">锁定</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope"> 
                <el-button
                  size="mini" type="primary" icon="el-icon-edit"
                  :disabled = "scope.row.uname == 'admin'"
                  @click="handleEdit(scope.row)">编辑</el-button>
                <el-button
                  size="mini" v-if="scope.row.lockstate == 1" type="warning"
                  :disabled = "scope.row.uname == 'admin'"
                  @click="handleDisable(scope.row)">锁定</el-button>
                <el-button
                  size="mini" v-if="scope.row.lockstate == 0" type="success"
                  @click="handleEnable(scope.row)">解锁</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  :disabled = "scope.row.uname == 'admin'"
                  @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="1"><br></el-col>
        <el-col :span="5">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="dto.page"
            :page-sizes="[5, 10, 20, 30]"
            :page-size="dto.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </el-col>
      </el-row>
    </el-card>
    <!-- 表单弹出框 -->
    <el-dialog :title="formtitle" :visible.sync="dialogEmployeeVisible" width="30%" @close="close('ruleForm')"  :modal-append-to-body="false">
      <el-form :model="employee" :rules="currentRules" ref="ruleForm">
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="uname">
          <el-input v-model="employee.uname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" prop="password" v-if="formtitle == '添加成员'">
          <el-input type="password" v-model="employee.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" :label-width="formLabelWidth" prop="checkPass"
        v-if="formtitle == '添加成员'">
          <el-input type="password" v-model="employee.checkPass" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="姓名" :label-width="formLabelWidth" prop="name">
          <el-input v-model="employee.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
          <el-input v-model="employee.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门角色" :label-width="formLabelWidth" prop="ids">
          <el-cascader
          v-model="employee.ids"
          :props="{ value: 'value',label: 'label',children: 'children',expandTrigger: 'hover'}"
          :options="departmentList"
          placeholder="请选择部门及角色"
          clearable
          :style="{ width: '100%' }"
          @change="handleChange"></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close('ruleForm')">取 消</el-button>
        <el-button type="primary" @click="handleConfirm('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data(){
    var validateCheckName = (rule, value, callback) => {
      if (this.formtitle == '编辑成员' && this.employee.uname == this.oldEmployee.uname && this.employee.name == this.oldEmployee.name && this.employee.phone == this.oldEmployee.phone && this.employee.rid == this.oldEmployee.rid){
        callback(new Error('请至少修改一项数据'));
      } else if (this.formtitle == '编辑成员' && this.employee.uname == this.oldEmployee.uname){
        callback();
      } else {
        this.$axios.get('/user/checkUname/' + value).then(res=>{
          if (res.data.code == 200) {
            if (res.data.data) {
              callback();
            } else {
              callback(new Error('您输入的用户名已存在'));
            }
          }
        })
      }
    };
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.employee.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass');
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.employee.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return{
      dto:{
        uname:'',
        did:'',
        rid:'',
        page:1,
        size:5
      },
      total:0,
      departmentList:[],
      roleList:[],
      employeeList:[],
      dialogEmployeeVisible:false,
      formtitle:'',
      formLabelWidth: '80px',
      employee:{
        id:'',
        uname:'',
        password:'',
        checkPass:'',
        name:'',
        rid:'',
        did:'',
        phone:'',
        ids:[]
      },
      oldEmployee:{},
      ruleAdd:{
        uname: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { validator: validateCheckName, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ],
        checkPass: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: validatePass2, trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { 
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/, 
            message: '请输入正确的手机号',
            trigger: 'blur'
          }
        ],
        ids: [
          { required: true, message: '请选择部门及角色', trigger: 'change' }
        ],
      },
      ruleEdit:{
        uname: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { validator: validateCheckName, trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { 
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/, 
            message: '请输入正确的手机号',
            trigger: 'blur'
          }
        ],
        ids: [
          { required: true, message: '请选择部门及角色', trigger: 'change' }
        ],
      },
    }
  },
  watch:{
     // 监听title的变化，动态切换规则集
     formtitle(newTitle) {
      this.currentRules = newTitle === '添加成员' ? this.ruleAdd : this.ruleEdit;
      // 如果需要，可以在这里触发表单的重新验证
      //this.$refs.ruleForm.validate();
    }
  },
  mounted(){
    this.getAllDepartmentList()
    this.getAllRoleList()
    this.getEmployeeList()
  },
  methods:{
    handleSizeChange(val) {
      this.dto.size = val
      this.getEmployeeList()
    },
    handleCurrentChange(val){
      this.dto.page = val
      this.getEmployeeList()
    },
    //重置查询表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    getAllDepartmentList(){
      this.$axios.get('/department/getDepartmentListForEmployee').then(res=>{
        this.departmentList = res.data.data
      })
    },
    getAllRoleList(){
      this.$axios.get('/role/getRoleListForEmployee').then(res=>{
        this.roleList = res.data.data
      })
    },
    getEmployeeList(){
      this.$axios.get('/user/getEmployeeList',{
        params: this.dto
      }).then(res=>{
        if(res.data.code == 200){
          this.employeeList = res.data.data.data
          this.total = res.data.data.total
        }
      })
    },
    close(formName){
      this.$refs[formName].clearValidate();
      this.dialogEmployeeVisible = false
    },
    handleAdd(){
      this.dialogEmployeeVisible = true
      this.formtitle = "添加成员"
      this.employee = {
        id:'',
        uname:'',
        name:'',
        password:'',
        checkPass:'',
        rid:'',
        phone:'',
        did:''
      }
    },
    handleEdit(row){
      this.oldEmployee = row
      this.dialogEmployeeVisible = true
      this.formtitle = "编辑成员"
      this.employee = {
        id:row.id,
        uname:row.uname,
        name:row.name,
        phone:row.phone,
        rid:'',
        ids:[row.role.department.id,row.role.id]
      }
    },
    handleChange(){
      this.employee.did = this.employee.ids[0]
      this.employee.rid = this.employee.ids[1]
    },
    handleConfirm(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.employee);
          if (this.formtitle == '添加成员') {
            this.$axios.post('/user/addEmployee',this.employee).then(res=>{
              if (res.data.code == 200) {
                this.$message({
                  message: '添加成功！',
                  type: 'success'
                });
                this.dialogEmployeeVisible = false
                this.getEmployeeList()
              }
            })
          }
          if (this.formtitle == '编辑成员') {
            this.handleChange()
            console.log(this.oldEmployee);
            this.employee.oldDid = this.oldEmployee.role.department.id
            this.$axios.put('/user/editEmployee',this.employee).then(res=>{
              if (res.data.code == 200) {
                this.$message({
                  message: '编辑成功！',
                  type: 'success'
                });
                this.dialogEmployeeVisible = false
                this.getEmployeeList()
              }
            })
          }     
        } else {
          return false;
        }
      }); 
    },
    handleEnable(row){
      this.$axios.put("/user/enableAccount/" + row.id).then(res=>{
        if(res.data.code == 200){
          this.$message({
            message: '启用成功！',
            type: 'success'
          });
          this.getEmployeeList()
        }
      })
    },
    handleDisable(row){
      this.$axios.put("/user/disableAccount/" + row.id).then(res=>{
        if(res.data.code == 200){
          this.$message({
            message: '禁用成功！',
            type: 'success'
          });
          this.getEmployeeList()
        }
      })
    },
    handleDelete(row){
      this.$confirm('此操作将永久删除该成员, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.delete('/user/deleteEmployee/' + row.id + '/' + row.role.department.id).then(res=>{
          if (res.data.code == 200) {
            if (res.data.data){
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.getEmployeeList()
            }
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    }
  }
}
</script>

<style scoped>
.box-card {
  margin-left:5vh;
  margin-right:2vh;
  margin-top: 3vh;
  height: 88vh;
}
</style>